import { useState, useRef } from "preact/hooks";
import { presets } from "./presets";
import { stopPropagation } from "./utilities";
import { settings } from "./settings";
import {
  hasIme,
  isSearchFocus,
  isPortrait,
  wordSignal,
  setWord,
} from "./signals";

const PresetBar = () => {
  const [move, setMove] = useState(false);
  const [pos, setPos] = useState(0);
  const scrollReference = useRef(null);
  return hasIme.value &&
    isSearchFocus.value &&
    settings.value.searchPart.showPreset ? (
    <footer
      class={`bg-base-100 sticky z-1000 m-auto inline-flex w-max max-w-(--screen-w) overflow-x-scroll rounded-md py-1 ${isPortrait.value ? "bottom-[0]" : "bottom-2"}`}
      onTouchStart={stopPropagation}
      onTouchMove={stopPropagation}
      onTouchEnd={stopPropagation}
      ref={scrollReference}
    >
      {presets.value.map((word) => (
        <button
          class="btn btn-ghost btn-xs mx-2"
          type="button"
          onTouchStart={(event) => {
            event.preventDefault();
            setPos(event.touches[0].clientX);
          }}
          onTouchMove={(event) => {
            setMove(true);
            if (scrollReference.current) {
              scrollReference.current.scrollLeft -=
                (event.changedTouches[0].clientX - pos) / 20;
            }
          }}
          onTouchEnd={() => {
            if (!move) {
              setWord(wordSignal.value + word);
            }
            setMove(false);
          }}
          key={word}
        >
          {word}
        </button>
      ))}
    </footer>
  ) : (
    void 0
  );
};

export default PresetBar;
